<template>
  <PageWrapper>
    <RoomStatusManage :loading="loading" :items="roomList" :roomTypeOpts="roomTypeOpts" @change="onRoomSelect" />
    <div class="bg-white mt-4 rounded">
      <div class="p-4 font-bold text-[18px]">预约列表</div>
      <BasicTable @register="register">
        <template #toolbar>
          <Button type="primary" @click="addOrdered">新增预约</Button>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                label: '签到',
                ifShow: record.status == OrderStatusEnum.Unsign,
                onClick: onOrderAction.bind(null, OrderStatusEnum.Signed, record),
              },
              {
                label: '续费',
                ifShow: record.status == OrderStatusEnum.Signed,
                onClick: onOrderAction.bind(null, OrderStatusEnum.Renewal, record),
              },
              {
                label: '取消',
                color: 'error',
                ifShow: record.status == OrderStatusEnum.Signed,
                onClick: onOrderAction.bind(null, OrderStatusEnum.Cancel, record),
              },
            ]"
          />
        </template>
        <template #source="{ record }">
          {{ getCustomSourceName(record.source) }}
        </template>
      </BasicTable>
    </div>

    <AddOrderedModal
      @register="modalRegister"
      :roomOptions="roomList"
      :roomTypeOpts="roomTypeOpts"
      :customSourceOpts="customSourceOpts"
      @confirm="onOrderModalConfirm"
    />

    <SignOrderedModal @register="signRegister" @confirm="onSignModalConfirm" />
    <RenewalTimeModal @register="renewalRegister" />
  </PageWrapper>
</template>

<script lang="ts" setup >
  import { ref } from 'vue';
  import { omit, get } from 'lodash-es';
  import { Button } from 'ant-design-vue';
  import { getRoomList } from '@/api/roomManage';
  import * as api from '@/api/ordered';
  import { useRequest } from '@vben/hooks';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { PageWrapper } from '@/components/Page';
  import RoomStatusManage from './RoomStatusManage.vue';
  import AddOrderedModal from './AddOrderedModal.vue';
  import SignOrderedModal from './SignOrderedModal.vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { OrderStatusEnum, tableColumns } from './settings';
  import { IOrderedData, IOrderedRecord } from '@/api/ordered';
  import { AddRoomParams } from '@/api/roomManage/model';
  import { getDictOpts } from '@/api/dictionary';
  import { DictionaryCodeEnum } from '@/enums/appEnum';

  const { data: roomList, loading, refresh: roomRefresh } = useRequest(getRoomList);
  const { data: orderList, loading: orderLoading, refresh: orderRefresh } = useRequest(getOrderedArr);
  const { data: roomTypeOpts } = useRequest(() => getDictOpts(DictionaryCodeEnum.RoomTypeCode))
  const { data: customSourceOpts } = useRequest(() => getDictOpts(DictionaryCodeEnum.CustomSourceCode))

  const [modalRegister, { openModal, closeModal }] = useModal();
  const [signRegister, { openModal: openSignModal, closeModal: closeSignModal }] = useModal();
  const [renewalRegister, { openModal: openRenewalModal, closeModal: closeRenewalModal }] = useModal();

  const selectRoom = ref<AddRoomParams>();

  const [register] = useTable({
    columns: tableColumns,
    loading: orderLoading,
    dataSource: orderList,
    actionColumn: {
      title: '操作',
      dataIndex: 'action',
      width: '120px',
      slots: { customRender: 'action' },
    },
  });

  function addOrdered() {
    openModal(true, { type: 'add' });
  }

  function onOrderModalConfirm() {
    closeModal();
    useMessage().createMessage.success('操作成功!');
    orderRefresh();
  }

  function getCustomSourceName(value: string) {
    const target = (customSourceOpts.value || []).find((item) => item.value == value);
    return get(target, 'label', '--')
  }

  async function getOrderedArr(): Promise<IOrderedData[]> {
    const rut: any[] = await api.getOrderedList();
    return rut.map((item, index) => {
      return {
        order: index + 1,
        ...item,
      };
    });
  }

  function onRoomSelect(item: AddRoomParams) {
    selectRoom.value = item;
  }

  function cancelOrderHandler(data: Partial<IOrderedRecord>) {
    const { destroy } = useMessage().createWarningModal({
        title: '提示',
        content: '是否取消预约?',
        onOk: async () => {
          try {
            data.status = OrderStatusEnum.Cancel;
            await api.editOrdered(data as IOrderedData);
            useMessage().createMessage.success('取消预约成功!');
            orderRefresh();
            roomRefresh();
          } catch (err) {
            destroy();
          }
        },
      });
  }

  /** 表格操作事件 */
  function onOrderAction(type: OrderStatusEnum, record: IOrderedRecord) {
    const data = omit(record, ['key', 'order', 'createDate', 'updateDate'])

    switch(type) {
      case OrderStatusEnum.Signed:
        openSignModal(true, data);
        break
      case OrderStatusEnum.Cancel:
        cancelOrderHandler(data);
        break
      case OrderStatusEnum.Renewal:
        openRenewalModal(true, data);
        break
      default:
        break
    }
  }

  function onSignModalConfirm() {
    useMessage().createMessage.success('操作成功!');
    closeSignModal();
    orderRefresh();
    roomRefresh();
  }
</script> 